import { logout} from '@/api/user'
import {login,getBusiness} from '@/api/business'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    businessId:'',
    businessPwd:'',
    businessName:'',
    businessPhone:'',
    businessEmail:'',
    loginmsg: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_LOGINMSG: (state, loginmsg) => {
    state.loginmsg = loginmsg
  },
  SET_BUSINESSID:(state,businessId) =>{
    state.businessId = businessId
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const  data  = response
        if(response.msg !== '登录成功'){
          commit('SET_LOGINMSG', data.msg)
        }else{
          commit('SET_LOGINMSG', data.msg)
          commit('SET_TOKEN', data.obj.businessName)
          commit('SET_BUSINESSID', data.obj.businessId)
          sessionStorage.setItem("businessId",data.obj.businessId)
          setToken(data.obj.businessName)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getBusiness(state.businessId).then(response => {
        commit('SET_AVATAR', '../../icons/icon.jpeg')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

